﻿using System;
using System.Collections.Generic;
using System.Data;
using DevExpress.Web;
using System.Drawing;
using ConfExpert.Utility;
using System.Web;


public partial class Stock : MemberPage
{
    DataTable dtDetails;
    string notUnique = "Customer,Season,Owner,OrderRef,CustomerCode,Brand,VendorCode,GrupppoTex,VendorCode;ValoreTex";

    protected void Page_Init(object sender, EventArgs e)
    {
        //Event i load olarak kullanınca KeyFieldName hatası veriyor.
          Bind();


    }

    protected void Page_Load(object sender, EventArgs e)
    {
        dtDetails = DataAccess.web2GetStokFields(CurrentTab);
        ASPxListBox lb = (ASPxListBox)ddeDetailLevel.FindControl("listBox");
        lb.Items.Clear();

        foreach (string item in dtDetails.Rows[0][0].ToString().Split(','))
        {
            if (chkRes.Checked)
            {
                if (!notUnique.Contains(item))
                {
                    lb.Items.Add(item, item);
                }
            }
            else
            {
                lb.Items.Add(item, item);
            }
        }

        //Aşağıdaki kısımlar olmayınca, filtre gibi callback lerden sonra template kayboluyor
        GridViewDataColumn gcImg = (GridViewDataColumn)gvRezerve.Columns["Scan"];
        if (gcImg != null)
            gcImg.DataItemTemplate = new Utils.PhotoColumnTemplate();

        GridViewDataColumn gcBestMatch = (GridViewDataColumn)gvRezerve.Columns["BestMatchQty"];
        if (gcBestMatch != null)
            gcBestMatch.DataItemTemplate = new Utils.KpiColumnTemplate();

        GridViewDataColumn gcAvailable = (GridViewDataColumn)gvRezerve.Columns["AvailableQty"];
        if (gcAvailable != null && Sessions.CurrentMember.CustomerId != 22)
        {
            if (IsReservationEnabled)
                gcAvailable.DataItemTemplate = new Utils.AvailableQtyTemplate();
            else
                gcAvailable.DataItemTemplate = new Utils.AvailableQtyReadOnlyTemplate();
        }

        GridViewDataColumn gcQtyInStock = (GridViewDataColumn)gvRezerve.Columns["QtyInStock"];
        if (gcQtyInStock != null)
        {
            gcQtyInStock.DataItemTemplate = new Utils.QtyInStockTemplate();
        }

        GridViewDataColumn gcQtyBlocked = (GridViewDataColumn)gvRezerve.Columns["BlockedQty"];
        if (gcQtyBlocked != null)
        {
            gcQtyBlocked.DataItemTemplate = new Utils.QtyBlocked();
        }

        btnSummary.Visible = (Sessions.CurrentMember.CustomerId == 20);
        
    }

    bool isUnique;

    public bool IsReservationEnabled
    {
        get
        {
            if (!chkRes.Checked)
            {
                return false;
            }
            else
            {
                return isUnique;
            }
        }
    }

    private string DetailLevel
    {
        get { return ddeDetailLevel.Text; }
        set { ddeDetailLevel.Text = value; }
    }

    private string CurrentTab
    {
        get
        {
            return Sessions.CurrentTab;
            //switch (tab.ActiveTabIndex)
            //{
            //    case 0:
            //        return ".";
            //    case 1:
            //        return "K";
            //    case 2:
            //        return "E";
            //}
            //return ".";
        }
    }

    protected void btnClose_click(object sender, EventArgs e)
    {
        Sessions.DetailLevel = DetailLevel;
        Bind();
    }

    protected void tab_ActiveTabChanged(object source, DevExpress.Web.TabControlEventArgs e)
    {
        switch (tab.ActiveTabIndex)
        {
            case 0:
                Sessions.CurrentTab = ".";
                break;
            case 1:
                Sessions.CurrentTab = "K";
                break;
            case 2:
                Sessions.CurrentTab = "E";
                break;
        }
        Bind();
    }

    protected void chkRes_CheckedChanged(object sender, EventArgs e)
    {
        if (chkRes.Checked)
        {
            string currentDL = DetailLevel;

            string newDL = "";
            foreach (string col in currentDL.Split(','))
            {
                if (!notUnique.Contains(col))
                    newDL += col + ",";
            }

            if (newDL.EndsWith(","))
                newDL = newDL.Substring(0, newDL.Length - 1);

            Sessions.DetailLevel = newDL;
            DetailLevel = newDL;
        }
        Bind();
    }

    protected void grdRolls_OnCustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        string parameter = e.Parameters;
        int PopupProductId = int.Parse(parameter);
        DataTable dtAvailableRolls = DataAccess.web2AvailableRolls(PopupProductId, CurrentTab);

        grdRolls.DataSource = dtAvailableRolls;
        grdRolls.DataBind();
        grdRolls.Selection.UnselectAll();

        //Grid de seçilmiş topları işaretler;
        foreach (DataRow dr in dtAvailableRolls.Rows)
        {
            if ((bool)dr["Selected"])
            {
                int rollId = (int)dr["RollId"];
                grdRolls.Selection.SelectRowByKey(rollId);
            }
        }

        grdRolls.Columns["Select"].Visible = IsReservationEnabled;
        grdRolls.Enabled = IsReservationEnabled;
    }

    protected void grdTinEye_OnCustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        string parameter = e.Parameters;
        int PopupProductId = int.Parse(parameter);
        //DataTable dtAvailableRolls = DataAccess.web2AvailableRolls(PopupProductId, CurrentTab);
        tinEye.TinyEyeSoapClient tEye = new tinEye.TinyEyeSoapClient();
        tEye.Search(PopupProductId);
        string productIds = tEye.Search(PopupProductId);
        DataTable dt = DataAccess.GetTinyEyeProducts(productIds,CurrentTab);
        gvTinEye.DataSource = dt;
        gvTinEye.DataBind();

        GridViewDataColumn gcImg = (GridViewDataColumn)gvTinEye.Columns["ProductId"];
        if (gcImg != null)
        {
            gcImg.DataItemTemplate = new Utils.MissingPhotoColumnTemplate();
            gcImg.Width = 50;
            gcImg.Caption = "Scan";
        }
           


        

        //grdRolls.DataSource = dtAvailableRolls;
        //grdRolls.DataBind();
        //grdRolls.Selection.UnselectAll();

        ////Grid de seçilmiş topları işaretler;
        //foreach (DataRow dr in dtAvailableRolls.Rows)
        //{
        //    if ((bool)dr["Selected"])
        //    {
        //        int rollId = (int)dr["RollId"];
        //        grdRolls.Selection.SelectRowByKey(rollId);
        //    }
        //}

        //grdRolls.Columns["Select"].Visible = IsReservationEnabled;
        //grdRolls.Enabled = IsReservationEnabled;
    }
    
    protected void grdBlocked_OnCustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        string parameter = e.Parameters;
        int PopupProductId = int.Parse(parameter);
        DataTable dtBlockeds = DataAccess.web2GetBlockedQtyDetail (PopupProductId);

        grdBlocked.DataSource = dtBlockeds;
        grdBlocked.DataBind();
    }
    #region Renklendirme
    //Available sütununu renklendirme
    protected void gvRezerve_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
    {
        if (gvRezerve.Columns["AvailableQty"] != null && e.DataColumn == gvRezerve.Columns["AvailableQty"])
        {
            if (e.CellValue == DBNull.Value || (decimal)e.CellValue == 0)
            {
                e.Cell.ForeColor = Color.Red;
            }
        }
    }

    //Satır renklendirme
    protected void gvRezerve_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType != DevExpress.Web.GridViewRowType.Data) return;
        if (!chkRes.Checked) return;
        if (!isUnique) return;

        //if (Session["ReservationStarted"] == null || (bool)ViewState["ReservationStarted"] == false) return;
        decimal requested = 0;
        decimal bestMatch = 0;
        decimal available = 0;

        if (e.GetValue("RequestedQty") != DBNull.Value) requested = (decimal)e.GetValue("RequestedQty");
        if (e.GetValue("BestMatchQty") != DBNull.Value) bestMatch = (decimal)e.GetValue("BestMatchQty");
        if (e.GetValue("AvailableQty") != DBNull.Value) available = (decimal)e.GetValue("AvailableQty");

        if (available == 0)
        {
            //e.Row.ForeColor = Color.Silver;
            //e.Row.ForeColor = Color.Red;
        }

        if (!(requested > 0))
            return;

        if (bestMatch == 0)
        {
            //e.Row.BackColor = Color.FromArgb(0xFF, 0xFF, 0x66);
            e.Row.BackColor = Color.FromArgb(0xFF, 0xFF, 0x66);
        }
        else if (requested == bestMatch)
        {
            //e.Row.BackColor = Color.FromArgb(0xFF, 0xFF, 0xCC);
            e.Row.BackColor = Color.FromArgb(0xFF, 0xFF, 0x66);
        }
        else if (requested < bestMatch)
        {
            //e.Row.BackColor = Color.FromArgb(0xFF, 0xFF, 0x99);
            e.Row.BackColor = Color.FromArgb(0xFF, 0xFF, 0x66);
        }
        else if (requested > bestMatch)
        {
            e.Row.BackColor = Color.FromArgb(0xFF, 0xFF, 0x66);
        }
    }
    #endregion


    private DataTable Bind()
    {
        DataSet ds = DataAccess.web2GetStok(Sessions.DetailLevel, CurrentTab);
        DataTable dt = ds.Tables[0];

        isUnique = (bool)ds.Tables[ds.Tables.Count - 1].Rows[0][0];
        pnlRes.Visible = IsReservationEnabled;

        gvRezerve.DataSource = dt;

        gvRezerve.Columns.Clear();
        gvRezerve.TotalSummary.Clear();

        foreach (DataColumn col in dt.Columns)
        {
            string colName = col.ColumnName.ToLower();
            if (colName == "productıd")
            {
                GridViewCommandColumn gcId = new GridViewCommandColumn();
                gcId.ShowSelectCheckbox = true;
                gcId.Caption = "Select";
                gvRezerve.Columns.Add(gcId);

                GridViewDataColumn gcImg = new GridViewDataColumn();
                gcImg.DataItemTemplate = new Utils.PhotoColumnTemplate();
                gcImg.Caption = "Scan";
                gcImg.CellStyle.Paddings.Padding = 1;
                gcImg.Width = 33;
                gcImg.CellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                gvRezerve.Columns.Add(gcImg);
            }
            else if (colName == "isforced")
            {
                GridViewDataTextColumn gcIF = new GridViewDataTextColumn();
                gcIF.Visible = false;
                gcIF.FieldName = "isForced";
                gvRezerve.Columns.Add(gcIF);
            }
            else if (colName == "availableqty" && Sessions.CurrentMember.CustomerId != 22)
            {
                GridViewDataTextColumn gcAQ = new GridViewDataTextColumn();
                gcAQ.Caption = "Available Qty";
                gcAQ.FieldName = "AvailableQty";

                if (IsReservationEnabled)
                    gcAQ.DataItemTemplate = new Utils.AvailableQtyTemplate();
                else
                    gcAQ.DataItemTemplate = new Utils.AvailableQtyReadOnlyTemplate();

                gcAQ.Settings.AutoFilterCondition = AutoFilterCondition.GreaterOrEqual;
                gcAQ.CellStyle.Wrap = DevExpress.Utils.DefaultBoolean.False;
                gcAQ.CellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;
                gcAQ.CellStyle.ForeColor = Color.Blue;
                gcAQ.CellStyle.Font.Underline = true;
                gcAQ.CellStyle.Cursor = "pointer";

                ASPxSummaryItem summary = new ASPxSummaryItem(gcAQ.FieldName, DevExpress.Data.SummaryItemType.Sum);
                summary.DisplayFormat = "∑ {0:n1} mt(s).";
                summary.ShowInColumn = col.ColumnName;
                gvRezerve.TotalSummary.Add(summary);

                gvRezerve.Columns.Add(gcAQ);
            }
            else if (colName == "qtyınstock")
            {
                GridViewDataTextColumn gcAQ = new GridViewDataTextColumn();
                gcAQ.Caption = "Qty in Stock";
                gcAQ.FieldName = "QtyInStock";

                gcAQ.DataItemTemplate = new Utils.QtyInStockTemplate();
                
                gcAQ.Settings.AutoFilterCondition = AutoFilterCondition.GreaterOrEqual;
                gcAQ.CellStyle.Wrap = DevExpress.Utils.DefaultBoolean.False;
                gcAQ.CellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;
                gcAQ.CellStyle.ForeColor = Color.Blue;
                gcAQ.CellStyle.Font.Underline = true;
                gcAQ.CellStyle.Cursor = "pointer";

                ASPxSummaryItem summary = new ASPxSummaryItem(gcAQ.FieldName, DevExpress.Data.SummaryItemType.Sum);
                summary.DisplayFormat = "∑ {0:n1} mt(s).";
                summary.ShowInColumn = col.ColumnName;
                gvRezerve.TotalSummary.Add(summary);

                gvRezerve.Columns.Add(gcAQ);
            }
            else if (colName == "blockedqty")
            {
                GridViewDataTextColumn gcAQ = new GridViewDataTextColumn();
                gcAQ.Caption = "Blocked Qty";
                gcAQ.FieldName = "BlockedQty";

                gcAQ.DataItemTemplate = new Utils.QtyBlocked();

                gcAQ.Settings.AutoFilterCondition = AutoFilterCondition.GreaterOrEqual;
                gcAQ.CellStyle.Wrap = DevExpress.Utils.DefaultBoolean.False;
                gcAQ.CellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;
                gcAQ.CellStyle.ForeColor = Color.Blue;
                gcAQ.CellStyle.Font.Underline = true;
                gcAQ.CellStyle.Cursor = "pointer";

                ASPxSummaryItem summary = new ASPxSummaryItem(gcAQ.FieldName, DevExpress.Data.SummaryItemType.Sum);
                summary.DisplayFormat = "∑ {0:n1} mt(s).";
                summary.ShowInColumn = col.ColumnName;
                gvRezerve.TotalSummary.Add(summary);

                gvRezerve.Columns.Add(gcAQ);
            }
            else if (colName == "bestmatchqty")
            {
                GridViewDataColumn gcKpi = new GridViewDataColumn();
                gcKpi.DataItemTemplate = new Utils.KpiColumnTemplate();
                gcKpi.Caption = "Qty To Reserve";
                gcKpi.FieldName = "BestMatchQty";
                gcKpi.Settings.AutoFilterCondition = AutoFilterCondition.GreaterOrEqual;
                gcKpi.CellStyle.Wrap = DevExpress.Utils.DefaultBoolean.False;
                ASPxSummaryItem summary = new ASPxSummaryItem("BestMatchQty", DevExpress.Data.SummaryItemType.Sum);
                summary.DisplayFormat = "∑ {0:n1} mt(s).";
                summary.ShowInColumn = col.ColumnName;
                gvRezerve.TotalSummary.Add(summary);
                gvRezerve.Columns.Add(gcKpi);
            }
            else
            {
                GridViewDataTextColumn gc = new GridViewDataTextColumn();
                gc.FieldName = col.ColumnName;
                gc.Settings.AutoFilterCondition = AutoFilterCondition.Contains;

                if (colName != "description")
                    gc.CellStyle.Wrap = DevExpress.Utils.DefaultBoolean.False;

                ASPxSummaryItem summary;
                if (colName == "article")
                {
                    summary = new ASPxSummaryItem(gc.FieldName, DevExpress.Data.SummaryItemType.Count);
                    summary.ShowInColumn = col.ColumnName;
                    summary.DisplayFormat = "∑ {0:n0} row(s)";
                    gvRezerve.TotalSummary.Add(summary);
                }

                if (colName.Contains("price"))
                {
                    gc.CellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;
                }

                else if (colName.Contains("qty") || colName.Contains("total"))
                {
                    gc.PropertiesTextEdit.DisplayFormatString = "#,#.0;#,#.0; ;";
                    gc.Settings.AutoFilterCondition = AutoFilterCondition.GreaterOrEqual;
                    summary = new ASPxSummaryItem(gc.FieldName, DevExpress.Data.SummaryItemType.Sum);
                    summary.DisplayFormat = "∑ {0:n1} mt(s).";
                    summary.ShowInColumn = col.ColumnName;
                    gvRezerve.TotalSummary.Add(summary);
                }

                gvRezerve.Columns.Add(gc);
            }
        }

        gvRezerve.Columns["BestMatchQty"].Visible = IsReservationEnabled;
        gvRezerve.Columns["RequestedQty"].Visible = IsReservationEnabled;
        gvRezerve.Columns["Select"].Visible = IsReservationEnabled;

        if (CurrentTab != ".")
        {
            GridViewColumn gc;
            gc = gvRezerve.Columns["BlockedQty"];
            if (gc != null)
            {
                gc.Visible = false;
            }

            gc = gvRezerve.Columns["ReservedQty"];
            if (gc != null)
            {
                gc.Visible = false;
            }
        }
        


        gvRezerve.SettingsPager.PageSize = 10000;

        if (chkRes.Checked && isUnique)
            gvRezerve.Styles.AlternatingRow.Enabled = DevExpress.Utils.DefaultBoolean.False;
        else
            gvRezerve.Styles.AlternatingRow.Enabled = DevExpress.Utils.DefaultBoolean.True;

        gvRezerve.DataBind();

        Bind7CSummary(ds);

        ConfExpertMaster m = (ConfExpertMaster)Master;
        m.TableToExport = dt;

        if (Sessions.CurrentMember.CustomerId == 1)
        {
            tab.Tabs[0].Visible = false;
        }

        return dt;
    }

    protected void gvHeader_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
    {
        if (e.VisibleIndex == gvHeader.VisibleRowCount - 1)
        {
            e.Cell.ForeColor = Color.Red;
        }
    }

    private void Bind7CSummary(DataSet ds)
    {
        if (Sessions.CurrentMember.CustomerId == 20)
        {
            gvHeader.Visible = true;
            gvHeader.DataSource = ds.Tables[1];
            gvHeader.DataBind();            
        }
        else
        {
            gvHeader.Visible = false;            
        }
    }

    protected List<int> SelectRollsBySubSetSum(List<int> pIds)
    {
        int hedef = 0;
        int.TryParse(txtQtyRequest.Text, out hedef);

        List<int> selectedRolls = new List<int>();

        if (hedef != 0)
        {
            DataTable availableRolls = DataAccess.web2AvailableRolls(pIds, CurrentTab);
            foreach (int pId in pIds)
            {
                decimal sum = 0;
                decimal maxVal = 0;
                decimal total = 0;
                decimal delta = 0;

                DataRow[] productRolls = availableRolls.Select(string.Format("ProductId={0}", pId));

                decimal[] degerler = new decimal[productRolls.Length];
                int[] rollIds = new int[productRolls.Length];

                List<List<decimal>> results = new List<List<decimal>>();

                for (int i = 0; i < productRolls.Length; i++)
                {
                    DataRow dr = productRolls[i];

                    decimal qty = (decimal)dr["Qty"];
                    int rollId = (int)dr["RollId"];

                    degerler[i] = qty;
                    rollIds[i] = rollId;
                    sum += qty;

                    if (qty > maxVal)
                    {
                        maxVal = qty;
                    }
                }

                if (hedef > sum)
                {
                    selectedRolls.AddRange(rollIds);
                    total = sum;
                }
                else
                {
                    while (delta <= maxVal)
                    {
                        Solver2 solver = new Solver2();
                        solver.delta = delta;
                        results = solver.Solve(hedef, degerler);
                        if (results.Count > 0)
                            break;

                        delta += 1;
                    }

                    if (results.Count > 0)
                    {
                        List<decimal> result = results[0];

                        for (int i = 0; i < result.Count; i++)
                        {
                            decimal value = result[i];
                            for (int j = 0; j < degerler.Length; j++)
                            {
                                decimal deger = degerler[j];
                                if (deger == value)
                                {
                                    selectedRolls.Add(rollIds[j]);
                                    total += value;
                                    degerler[j] = 0;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

        }
        return selectedRolls;
    }

    protected void gvRezerve_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        List<int> pIds = gvRezerve.GetSelectedFieldValues("ProductId").ConvertAll<int>(delegate(object i) { return (int)i; });

        switch (e.Parameters)
        {
            case "all":
                DataAccess.web2SetSelectedProducts(pIds, new List<int>(), -1, CurrentTab);
                break;
            case "manual":
                DataAccess.web2SetSelectedProducts(pIds, SelectRollsBySubSetSum(pIds), decimal.Parse(txtQtyRequest.Text), CurrentTab);
                break;
            case "cancel":
                DataAccess.web2SetSelectedProducts(pIds, new List<int>(), 0, CurrentTab);
                break;
            case "rollSelection":
                List<int> rIds = grdRolls.GetSelectedFieldValues("RollId").ConvertAll<int>(delegate(object i) { return (int)i; });
                DataAccess.web2SetSelectedProducts(pIds, rIds, -2, CurrentTab);
                break;
        }

        Bind();
        gvRezerve.Selection.UnselectAll();
    }

    protected void btnFinish_Click(object sender, EventArgs e)
    {
        SetForces();

        DataSet ds = DataAccess.web2InsRezerve(int.Parse(cmbBrand.Value.ToString()), int.Parse(cmbSeason.Value.ToString()), int.Parse(cmbDuration.Value.ToString()), txtNotes.Text, txtOrderRef.Text, txtReservedBy.Text, txtEmail.Text);
        int RezerveId = (int)ds.Tables[0].Rows[0][0];

        Sessions.Brand = cmbBrand.SelectedItem.Text;
        Sessions.Season = cmbSeason.SelectedItem.Text;
        Sessions.Duration = cmbDuration.Value.ToString() + " day(s)";
        Sessions.Notes = txtNotes.Text; ;
        Sessions.OrderRef = txtOrderRef.Text;
        Sessions.RequestId = RezerveId;
        Sessions.ReservedBy = txtReservedBy.Text;
        Sessions.email = txtEmail.Text;
        Sessions.RezerveSummary = ds.Tables[1];

        Response.Redirect("ReservationReport.aspx");
    }

    private void SetForces()
    {
        DataTable dtForce = new DataTable();
        dtForce.Columns.Add("ProductId", typeof(int));

        foreach (string fe in Request.Form.AllKeys)
        {
            if (fe.StartsWith("rb_"))
            {
                var checkboxValue = Request.Form[fe].ToString();
                int pId = int.Parse(fe.Replace("rb_", ""));
                if (checkboxValue == "1")
                {
                    dtForce.Rows.Add(pId);
                }
            }
        }

        DataAccess.web2SetSelectionForce(dtForce, CurrentTab);
    }

    protected void tab_ActiveTabChanging(object source, DevExpress.Web.TabControlCancelEventArgs e)
    {
        if (IsReservationEnabled)
            SetForces();
    }
  

  
   
}